<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Hupu extends FaXingBase
{

    public function register($params)
    {

        $cid = $params['cid'];
        // 获取用户信息
        $sign_data = ['appid'=>$this->extdata['appid'],'access-token'=>$params['access_token']];
        $sign = $this->signData($sign_data, $this->extdata['APPKEY']);

        $url = "https://open.hupu.com/".$this->extdata['appid']."/containerH5/getUserId?sign=".$sign;
        dump($url);
        $res = curlRequest($url,[],$sign_data,"GET", 'form');
        dump($res);exit;
        $result = json_decode($res,true);


        $account = $cid."_".$result['data']['userId'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            $data['is_age'] = 0;

            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }


    public function order($order)
    {
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();

        $account = get_player($order['uid'],'account');
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['APPKEY']); // 回传验证
        $data = [
            'app_id' => $this->extdata['APPID'],
            'user_id' => $account[1],
            'zone_id'=>$role['sid'],//区服id
            'zone_name'=>$role['sid'],//区服名称
            'role_id' => $role['role_id'],
            'role_name' => $role['role_name'],
            'game_order_id' => $order['order_no'],
            'order_amount'=> $order['amount'] * 100,//金额 整数：分
            'prop_id'=>rand(000000,999999),//商品id
            'prop_name'=>$order['goods_name'],//商品名称
            'extra'=> json_encode(["order_no"=>$order['order_no'],'sign'=>$sign]), // $order['order_no']."|".$sign 回传验证
        ];
        $data['sign'] = $this->signData($data,$this->extdata['APPKEY']);
        return $data;
    }

    public function check_order($params)
    {
        $ord_arr = json_decode($params['extra'],true);
        $order_no = $params['game_order_id'];
        $sign = $ord_arr['sign'];

        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['APPKEY']);

        if($order_sign != $sign){
            echo json_encode(['code'=>403,'message'=>'签名错误']);exit;
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if(!$this->check_sign($params,$this->extdata['APPKEY'])){
            echo json_encode(['code'=>403,'message'=>'签名错误']);exit;
        }

        if($order['amount'] * 100 != $params['order_amount']){
            echo json_encode(['code'=>500,'message'=>'处理失败']);exit;
        }

        $order->trade_no = $params['gather_order_id'];
        $order->save();

        return $order;
    }

    public function create_role($params)
    {
        $url = "https://sdkapi.duoyou.com/games/role?";

        $redis = new Redis();
        $player = $redis->get($params['token']);
        $third_data = $player['third_data'];
        $account = explode("_",$player['account']);
        $data = [
            'app_id' => $this->extdata['APPID'],
            'user_id' => $account[1],
            'zone_id' =>(int) $params['sid'],
            'zone_name' => $params['sid'],
            'role_id' => $params['role_id'],
            'role_name' => $params['role_name'],
            'role_level' => $params['role_level'],
            'vip_level' => "0",
            'power' => $params['role_power'],
            'rebirth_times' => "0",
            'extra' => ""
        ];
        $data['sign'] = $this->signData($data,$this->extdata['APPKEY']);
        $data['push'] = 1;
        $res = file_get_contents($url.http_build_query($data));
        echo $res;exit;
    }


    public function message($message,$order)
    {
        echo $message === 'success' ? json_encode(['code'=>200,'message'=>'回调成功']) :  json_encode(['code'=>500,'message'=>'处理失败']);
        exit;
    }

    private function signData($data, $secret) {
        ksort($data);
        foreach ($data as $k => $v) {
            $tmp[] = $k . '=' . urlencode($v);
        }
        $str = implode('&', $tmp) . $secret;

        return md5($str);
    }

    protected function check_sign($params, $key)
    {
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);

        $check_sign = $this->signData($sign_data,$key);

        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}